package com.qipay.admin.withdraw.service;

import com.alibaba.fastjson.JSONObject;
import com.qipay.baas.model.Holiday;
import com.qipay.mapper.HolidayMapper;
import com.qipay.utils.MD5Util;
import com.qipay.utils.RSAUtils;
import com.qipay.utils.XmlUtils;
import org.apache.commons.lang3.StringUtils;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;

import static com.qipay.sp.excutor.AbstractExcutor.doJsonPost;
import static com.qipay.sp.excutor.AbstractExcutor.http;

/**
 * 代付的逻辑
 */
@Service
public class WithdrawAnotherService {
    private static Logger logger = LoggerFactory.getLogger(WithdrawAnotherService.class);
    private String df_private_key = "MIICdQIBADANBgkqhkiG9w0BAQEFAASCAl8wggJbAgEAAoGBALJ9J1jT6rDsNVIBxVqLLuIN8ujGV2YwEkFO708QU8J90coeG0UsRXbHDGTymbNEvTnO5L3pEp9mxW28bSD0ICtXdmPGhgMkhVT7nEuYyydF4dVIGGYbh0teKXD9LyqT4K8vvM8X0bVLuGanaRtvClfG/15i/12f92LYH98FCUU1AgMBAAECgYA0917NxVVH21CXXV8rV1I6UtlaqkEVWf6Q0tPBKp8wgBXZXMXK6TBT5w2Oh0+FG0jr9rF6ice09dJwlhHsTYWd18kAVNNTS2ZQA8EWeXL/3Koan3NVeHX04Sbe8KTCHTywOIUOc9gaVtg8cPxVG06UaUjl4lXOH+cYg7YP7tg6oQJBAOYI2RWf8x1Xui4sGUa1N5TxizulFu67pVC9BbkvghXX95NKpoLgc5flbe9qJplML2v/D3+UAFcDymH3AWMrrHsCQQDGotNGmKkpEM+jnfm82Ndeqxy/E7tGVwEMiB0HgQsjYYYnYYicBFdN2oKnc98lhD4n25EwWY/Bxk7rs0u3314PAkALyyhWE31DY9wHwfsJxQC0gi3BQRWL59Lx8L76X5UryYbH5mvjCd7jSr/4JlkUQvOrdcg1okDiNS+LFj7b9sFBAkBDnQEVsrlCBTroksmDgrwsuUobsHe6xbrRrTNUbpSAAp5LoWOC1+dv1MVMgqCegJk3sAGH17SbXQlYKbvIZvv5AkAGi87Twa8UnAr75ZN1nLHHMmSOxUezBE5blVMQ1Bgcof6SnIKqX/wPHfTICOhjOqGmjq9Ab3bZLr28PdUZVg9k";
    private String df_public_key = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDYBQIUUl4S5TVLxbTH9F9/Xke7TdbyqMvGWGDJ8yMp/QR2Kg+k5FEkEVelsilMKq+wmqgxGpfpKM1KPOd6wTggDyqWKD33MzNDN+QzMm1Luqr6sgUCu5cxSyvOSrFtaM6jweQa5QmAR6zM4URs45LoJ+gJM4sQpjYUrQc9zMcGAQIDAQAB";
//    private String df_url = "http://150.109.60.221:7780/transferAdmin/x2xtsfpay/doTransferApi.action";
    private String df_url = "http://47.101.45.51:7780/transferAdmin/x2xtsfpay/doTransferApi.action";

    @Autowired
    HolidayMapper holidayMapper;
    /**
     *  八维码代付接口，请求代付（管理员提现）
     * @return
     * @throws UnsupportedEncodingException
     */
    @Transactional
    public Map<String,Object> anotherApply(Map<String, Object> paramsHead,Map<String, Object> paramsData) throws Exception {
        Map<String, Object>params = new HashMap<>();
        params.putAll(paramsHead);params.putAll(paramsData);
        String sign = MD5Util.getRSAValue(params,df_private_key);
        paramsHead.put("sign",sign);
        String xmlHead=XmlUtils.toXmlString(paramsHead,"head");

        String xmlDataContent=XmlUtils.toXmlString(paramsData,"data");
        String dataDesc = RSAUtils.encryptByPublicKey(xmlDataContent.substring(6,xmlDataContent.length()-7).getBytes(),df_public_key);
        String xmlData = "<data>"+dataDesc+"</data>";
        String xmlStr="<xml>"+xmlHead+xmlData+"</xml>";

        //--------插入日志
        Holiday reqLog = new Holiday();
        reqLog.setDate(xmlStr);//请求报文
        reqLog.setIsHoliday((byte)2);//请求类型，1表示查询,2表示代付

        String result = httpXml(xmlStr,df_url);

        reqLog.setName(result);//响应报文
        holidayMapper.insert(reqLog);
        //---------日志结束

        if (StringUtils.isBlank(result)) {
            throw new Exception("请求乐娱的代付接口失败");
        }
        Document document =DocumentHelper.parseText(result);
        Element root = document.getRootElement();
        Element elements = root.element("head");
        Element element2 = root.element("data");
        Map<String,Object>resultMap = new HashMap<>();
        if("0000".equals(elements.element("respCd").getTextTrim())){
            resultMap.put("result_code", "0");
            resultMap.put("message", elements.element("respMsg").getTextTrim());
        }else {
            resultMap.put("result_code", "1");
            resultMap.put("message", elements.element("respMsg").getTextTrim());
        }

        return resultMap;
    }

    /**
     * 乐娱--查询余额
     * @param
     * @return
     */
    public Map<String, Object> findDfBalance(Map<String, Object> paramsHead,Map<String, Object> paramsData) throws Exception {
        Map<String, Object>params = new HashMap<>();
        params.putAll(paramsHead);params.putAll(paramsData);
        String sign = MD5Util.getRSAValue(params,df_private_key);
        paramsHead.put("sign",sign);
        String xmlHead=XmlUtils.toXmlString(paramsHead,"head");
        String xmlDataContent=XmlUtils.toXmlString(paramsData,"data");

        String dataDesc = RSAUtils.encryptByPublicKey(xmlDataContent.substring(6,xmlDataContent.length()-7).getBytes(),df_public_key);
        String xmlData = "<data>"+dataDesc+"</data>";
        String xmlStr="<xml>"+xmlHead+xmlData+"</xml>";

        //--------插入日志
        Holiday reqLog = new Holiday();
        reqLog.setDate(xmlStr);//请求报文
        reqLog.setIsHoliday((byte)1);//请求类型，1表示查询,2表示代付
        String result = httpXml(xmlStr,df_url);
        reqLog.setName(result);//响应报文
        holidayMapper.insert(reqLog);
        //---------日志结束

        Document document =DocumentHelper.parseText(result);
        Element root = document.getRootElement();
        Element elements = root.element("head");
        Element element2 = root.element("data");
        Map<String,Object>resultMap = new HashMap<>();
        if("0000".equals(elements.element("respCd").getTextTrim())){
            resultMap.put("result_code", "0");
            resultMap.put("allAmt", element2.element("allAmt").getTextTrim());//商家实时可用余额返回
            resultMap.put("freezeAmt", element2.element("freezeAmt").getTextTrim());//正在申请提现的金额
            resultMap.put("transferAmt", element2.element("transferAmt").getTextTrim());//已经转账的金额
            resultMap.put("allFee", element2.element("allFee").getTextTrim());//总的手续费，已收取的
            resultMap.put("proFee", element2.element("proFee").getTextTrim());//对私单笔手续费
            resultMap.put("proRate", element2.element("proRate").getTextTrim());//对私手续费费率
            resultMap.put("pubFee", element2.element("pubFee").getTextTrim());
            resultMap.put("pubRate", element2.element("pubRate").getTextTrim());
            resultMap.put("wStatus", element2.element("wStatus").getTextTrim());//钱包状态，1可用 0不可用
        }else{
            resultMap.put("result_code", "1");
            resultMap.put("message", elements.element("respMsg").getTextTrim());
        }
        return resultMap;
    }


    //发送请求
    public static String httpXml(String xmlStr, String url) {
        URL u = null;
        HttpURLConnection con = null;
        // 尝试发送请求
        try {
            u = new URL(url);
            con = (HttpURLConnection) u.openConnection();
            //// POST 只能为大写，严格限制，post会不识别
            con.setRequestMethod("POST");
            con.setDoOutput(true);
            con.setDoInput(true);
            con.setUseCaches(false);
            con.setRequestProperty("Content-Type", "text/xml");
            OutputStreamWriter osw = new OutputStreamWriter(con.getOutputStream(), "UTF-8");
            osw.write(xmlStr);
            osw.flush();
            osw.close();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (con != null) {
                con.disconnect();
            }
        }

        // 读取返回内容
        StringBuffer buffer = new StringBuffer();
        try {
            //一定要有返回值，否则无法把请求发送给server端。
            BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream(), "UTF-8"));
            String temp;
            while ((temp = br.readLine()) != null) {
                buffer.append(temp);
                buffer.append("\n");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println("pay sendPost response body : " + buffer.toString());
        return buffer.toString();
    }

    /**
     * 拼接字符串
     * @param maps
     * @return
     */
    public String generateStr(Map<String,Object>maps){
        SortedMap<String, Object> params=new TreeMap<String, Object>();
        for (String mapKey : maps.keySet()) {
            params.put(mapKey, maps.get(mapKey));
        }

        StringBuilder sb=new StringBuilder();
        for (String keyItem : params.keySet()) {
            if(params.get(keyItem)!=null&&!params.get(keyItem).toString().equals("")
                    &&!keyItem.equals("sign")&&!keyItem.equals("Sign")&&
                    !keyItem.equals("signature")&&!keyItem.equals("signData")){
                sb.append(params.get(keyItem).toString());
            }
        }
        String bunch=sb.toString();
        return bunch;
    }

    /**
     * 查询企鹅代付余额
     * @param paramsData
     * @return
     */
    public HashMap<String, String> findQeBalance(Map<String, Object> paramsData) {
        HashMap<String, String> resultMap = new HashMap<>();
        String result = doJsonPost("http://abc.huixinbaoli.com:8092/posm/mercbalqry.tran?olpdat=" + JSONObject.toJSONString(paramsData), "");
        Holiday reqLog = new Holiday();
        reqLog.setDate( JSONObject.toJSONString(paramsData));//请求报文
        reqLog.setIsHoliday((byte)3);//请求类型，1表示查询,2表示代付
        reqLog.setName(result);//响应报文
        holidayMapper.insert(reqLog);
        if (StringUtils.isNotBlank(result)) {
            JSONObject jsonObject = JSONObject.parseObject(result);
            if ("000000".equals(jsonObject.getString("RSPCODE"))) {
                resultMap.putIfAbsent("status", "0");
                resultMap.putIfAbsent("allMoney", jsonObject.getString("BALD0"));
                resultMap.putIfAbsent("t1Money", jsonObject.getString("BALT1"));
                resultMap.putIfAbsent("djMoney", jsonObject.getString("BALFZ"));
            } else {
                resultMap.putIfAbsent("status", jsonObject.getString("1"));
                resultMap.putIfAbsent("msg", jsonObject.getString("RSPMSG"));
            }
        }
        return resultMap;
    }

    public Map<String, String> qeApply(Map<String, String> paramsData) {
        HashMap<String, String> resultMap = new HashMap<>();
        String md5Value = MD5Util.sign(paramsData.get("instId") + paramsData.get("mercId") + paramsData.get("mercOrderId") +paramsData.get("stlDate")
                +paramsData.get("stlTime") +paramsData.get("stlAmt") +paramsData.get("stlAcctNo") +"BP7lJUYPGyk30Yav1dbZ3freK", "utf-8");
        paramsData.put("md5value", md5Value);
        String result = doJsonPost("http://abc.huixinbaoli.com:8092/posm/mercdfreq.tran?olpdat=" + JSONObject.toJSONString(paramsData), "");
        Holiday reqLog = new Holiday();
        reqLog.setDate( JSONObject.toJSONString(paramsData));//请求报文
        reqLog.setIsHoliday((byte)4);//请求类型，1表示查询,2表示代付
        reqLog.setName(result);//响应报文
        holidayMapper.insert(reqLog);
        if (StringUtils.isNotBlank(result)) {
            JSONObject jsonObject = JSONObject.parseObject(result);
            if ("000000".equals(jsonObject.getString("RSPCODE"))) {
                resultMap.putIfAbsent("status", "0");
                resultMap.putIfAbsent("allMoney", jsonObject.getString("BALD0"));
                resultMap.putIfAbsent("t1Money", jsonObject.getString("BALT1"));
                resultMap.putIfAbsent("djMoney", jsonObject.getString("BALFZ"));
            } else {
                resultMap.putIfAbsent("status", jsonObject.getString("1"));
                resultMap.putIfAbsent("msg", jsonObject.getString("RSPMSG"));
            }
        }
        return resultMap;
    }

    public HashMap<String, String> findYsfBalance(Map<String, Object> paramsData) {
        HashMap<String, String> resultMap = new HashMap<>();
        String result = http("http://api.marketfree.top/agentPayment/payBalanceQuery", paramsData);
        Holiday reqLog = new Holiday();
        reqLog.setDate(JSONObject.toJSONString(paramsData));//请求报文
        reqLog.setIsHoliday((byte)5);//请求类型，1表示查询,2表示代付
        reqLog.setName(result);//响应报文
        holidayMapper.insert(reqLog);
        if (StringUtils.isNotBlank(result)) {
            JSONObject jsonObject = JSONObject.parseObject(result);
            if ("succ".equals(jsonObject.getString("status"))) {
                resultMap.putIfAbsent("status", "0");
                resultMap.putIfAbsent("allMoney", jsonObject.getString("errMsg"));
            } else {
                resultMap.putIfAbsent("status", "1");
                resultMap.putIfAbsent("msg", jsonObject.getString("errMsg"));
            }
        }
        return resultMap;
    }

    public Map<String, String> ysfApply(Map<String, Object> paramsData) {
        String result = http("http://api.marketfree.top/agentPayment/paySingle", paramsData);
        HashMap<String, String> resultMap = new HashMap<>();
        Holiday reqLog = new Holiday();
        reqLog.setDate( JSONObject.toJSONString(paramsData));//请求报文
        reqLog.setIsHoliday((byte)6);//请求类型，1表示查询,2表示代付
        reqLog.setName(result);//响应报文
        holidayMapper.insert(reqLog);
        if (StringUtils.isNotBlank(result)) {
            JSONObject jsonObject = JSONObject.parseObject(result);
            if ("succ".equals(jsonObject.getString("status"))) {
                resultMap.putIfAbsent("status", "0");
                resultMap.putIfAbsent("msg", "提交成功");
            } else {
                resultMap.putIfAbsent("status", "1");
                resultMap.putIfAbsent("msg", jsonObject.getString("errMsg"));
            }
        }
        return resultMap;
    }
}
